package xx.codeflower.panoramio;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.briansteen.utils.GeoPosition;

/**
 * 
 * @author Denny Koch
 * 
 * Send a com.briansteen.utils.GeoPosition and get back a xx.codeflower.panoramio.PanoramioResult
 *
 */
public class PanoramioRequest {
	
	
	// Quick 'n dirty 
	public ArrayList<GeoPosition> get(GeoPosition position, float areaSize, String order, String set, String size) {
		
		String res = "";
		
		ArrayList<GeoPosition> gps = new ArrayList<GeoPosition>();
		
		InputStream is = null;		  
		try {
			URL url = new URL("http://www.panoramio.com/map/get_panoramas.php?order="+order+"&set="+set+"&from=0&to=100&minx="+(position.latitude-(areaSize/2))+"&miny="+(position.longitude-(areaSize/2))+"&maxx="+(position.latitude+(areaSize/2))+"&maxy="+(position.longitude+(areaSize/2))+"&size=medium"); 
			is = url.openStream(); 
			res = new Scanner( is ).useDelimiter( "\\Z" ).next(); 
		} catch ( Exception e ) { 
			e.printStackTrace();
		} finally {
			if ( is != null ) 
				try { is.close(); } catch ( IOException e ) { } 
		} 		
	
		try {
			JSONObject jos = new JSONObject(new JSONTokener(res));
			JSONArray  ja = jos.getJSONArray("photos");
			for(int i = 0; i < ja.length(); i++) {
				gps.add(
						new GeoPosition(
										(float)ja.getJSONObject(i).getDouble("latitude"),
										(float)ja.getJSONObject(i).getDouble("longitude")
										)
						);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return gps;
	}
	
}
